package edu.unika.aifb.graphindex.importer.db.metadata;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Table implements Serializable{
	private static final long serialVersionUID = -6379950442404728756L;
	private String name;
	private String schema;
	private Map<String, Column> columns = new HashMap<String, Column>();
	private Map<String, ForeignKeyConstraint> foreignKeys = new HashMap<String, ForeignKeyConstraint>();
	public Table(){
		
	}
	public Table(String name){
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSchema() {
		return schema;
	}
	public void setSchema(String schema) {
		this.schema = schema;
	}
	public void addColumn(Column column){
		columns.put(column.getName(), column);
	}
	
	public Column getColumn(String name){
		return columns.get(name);
	}
	
	public void addForeignKeyConstraint (String name, Column sourceColumn, Column targetColumn){
		ForeignKeyConstraint foreignKeyConstraint = foreignKeys.get(name);
		targetColumn.setPrimaryKey(true);
		if(foreignKeyConstraint != null){
			foreignKeyConstraint.addColumnReference(sourceColumn, targetColumn);
		}else{
			foreignKeyConstraint = new ForeignKeyConstraint(name, sourceColumn, targetColumn);
			this.foreignKeys.put(name, foreignKeyConstraint);
		}
	}
	
	public Set<Column> getPrimaryKeyColumns(){
		Set<Column> primaryKeyColumns = new HashSet<Column>();
		for(Column column : columns.values()){
			if(column.isPrimaryKey()){
				primaryKeyColumns.add(column);
			}
		}
		return primaryKeyColumns;
	}
	
	public boolean isForeignKey(Column column){
		for(ForeignKeyConstraint foreignKey : foreignKeys.values())
			if(foreignKey.getSourceColumns().contains(column))
				return true;
		return false;
	}
	
	public ForeignKeyConstraint getForeignKeyConstraint(String name){
		return foreignKeys.get(name);
	}
	
	public Set<String> getForeignKeyNames(){
		return foreignKeys.keySet();
	}
	
	public Set<Column> getForeignKeyColumns(){
		Set<Column> foreignKeyColumns = new HashSet<Column>();
		for(ForeignKeyConstraint foreignKey : foreignKeys.values()){
			foreignKeyColumns.addAll(foreignKey.getSourceColumns());
		}
		return foreignKeyColumns;
	}
	
	public Collection<Column> getColumns() {
		return columns.values();
	}
	
	public String toString(){
		return name;
	}
}
